package com.lujieni.sentinel;



import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableDiscoveryClient
public class Sentinel {

    public static void main(String[] args) {
        //initFlowRules();
        //initDegradeRule();
        SpringApplication.run(Sentinel.class, args);
    }


    // qps 限流
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("hello");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1);
        rules.add(rule);

        rule = new FlowRule();
        rule.setResource("bye");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1);
        rules.add(rule);

        FlowRuleManager.loadRules(rules);
    }

    // 熔断降级
    private static void initDegradeRule(){
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource("degrade");
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        // 熔断类型的值，如果是慢调用就是慢调用的值，单位是毫秒; 异常比例 / 异常个数 模式下为对应的值
        rule.setCount(3); // 出现2次异常就熔断
        // 熔断的最小请求数，请求数小于该值时，及时异常比例超过阈值也不会熔断
        rule.setMinRequestAmount(5);
        rule.setTimeWindow(30); // 熔断的时长，时间单位是秒
        rule.setStatIntervalMs(60 * 1000);
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }


}

